package com.htudata.common.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.io.PrintWriter;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.htudata.common.enums.A2CodeEnum;
import com.htudata.core.util.ResultGenerator;
import com.htudata.core.util.operation.HttpOperationUtils;
import com.htudata.core.util.operation.UrlOperationUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class TokenService {

  public String validateToken(String a2, String a2InfoUrl) throws Exception{
    String url = a2InfoUrl.replace("{a2}", URLEncoder.encode(a2, "UTF-8"));
    return HttpOperationUtils.sendGet(UrlOperationUtils.getUrlWithoutParam(url),
            UrlOperationUtils.getUrlParamFromUrl(url), "UTF-8");
  }
  
  public String validateToken(HttpServletRequest request, HttpServletResponse response, String tokenJson) throws Exception{
    JSONObject root = JSON.parseObject(tokenJson);
    if (root != null && root.getJSONObject("data").getIntValue("result") == 1) {
      if (request != null)
        request.setAttribute("a2Info", root.getJSONObject("data").getString("a2Info"));
      return root.getJSONObject("data").getString("a2Info");
    }
    return null;
  }
  
  public void writeResultWithA2Status(HttpServletResponse response) throws Exception {
    JSONObject resultWithA2Status = ResultGenerator.genResultWithA2Status(ResultGenerator.genResult("0", null)
            , A2CodeEnum.code_0
            .getCode());
    PrintWriter out = response.getWriter();
    IOUtils.write(resultWithA2Status.toJSONString(), out);
    IOUtils.closeQuietly(out);
  }
  
  public static long getUserId(HttpServletRequest request) throws Exception{
    long result = -1L;
    if (request == null)
      return result;
    result = getUserId(request.getAttribute("a2Info") + "");
    return result;
  }
  
  public static long getUserId(String a2Info) throws Exception {
    long result = -1L;
    result = JSONArray.parseObject(a2Info).getLongValue("userId");
    return result;
  }
  
  public static long getRoleType(HttpServletRequest request) throws Exception {
    long result = -1L;
    if (request == null)
      return result;
    result = getRoleType(request.getAttribute("a2Info") + "");
    return result;
  }
  
  public static long getRoleType(String a2Info) throws Exception {
    long result = -1L;
    result = JSONArray.parseObject(a2Info).getLongValue("roleType");
    return result;
  }
}
